package com.hc.ex;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.enums.ResultEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 异常统一处理类
 * @author 梁云亮
 */
@Log4j2
@RestControllerAdvice //表示定义全局控制器异常处理
public class GlobalExceptionHandler {

    /**
     * 对系统中抛出的用户自定义异常进行处理
     *
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(GlobalException.class)//会优先匹配精确的异常
    public Result exceptionHandler(HttpServletRequest request, GlobalException e) throws Exception {
        //日志记录异常
        log.info("Request URL: {}, Exception: {}", request.getRequestURL(), e);

        HashMap<String, String> data = new HashMap<>();
        data.put("url", request.getRequestURL().toString());
        data.put("msg", e.getMessage());

        return ResultUtil.fail(e.getCode(), e.getMessage(), data);
    }

    /**
     * 参数错误异常
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})//针对性异常处理，可对每种异常针对性处理。
    public Result handleException(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult result = validException.getBindingResult();
            StringBuffer errorMsg = new StringBuffer();
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    errorMsg.append(fieldError.getDefaultMessage()).append(",");
                    log.error("### 请求参数错误：{" + fieldError.getObjectName() + "},field{" + fieldError.getField() + "},errorMessage{" + fieldError.getDefaultMessage() + "}");
                });
            }
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            if (bindException.hasErrors()) {
                log.error("### 请求参数错误: {}", bindException.getAllErrors());
            }
        }
        return ResultUtil.fail(ResultEnum.PARAM_IS_INVALID);
    }

    /**
     * 对所有的异常进行处理
     *
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class) //会优先匹配精确的异常
    public Result exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        //日志记录异常
        log.info("Request URL: {}, Exception: {}", request.getRequestURL(), e);
        return ResultUtil.fail(ResultEnum.INTERNAL_SERVER_ERROR);
    }
}
